/***************************************************************************
 *   Copyright (C) 2008 by András Bécsi                                    *
 *   andrewbecsi @ yahoo . co . uk                                         *
 *                                                                         *
 *   This source file is part of the Qtdict project.                       *
 *                                                                         *
 *   This program is free software; you can redistribute it and/or modify  *
 *   it under the terms of the GNU General Public License as published by  *
 *   the Free Software Foundation; either version 2 of the License, or     *
 *   (at your option) any later version.                                   *
 *                                                                         *
 *   This program is distributed in the hope that it will be useful,       *
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
 *   GNU General Public License for more details.                          *
 *                                                                         *
 *   You should have received a copy of the GNU General Public License     *
 *   along with this program; if not, write to the                         *
 *   Free Software Foundation, Inc.,                                       *
 *   59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *
 ***************************************************************************/

#include "downloader.h"

Downloader::Downloader(QObject *parent):QObject(parent) {
    http = new QHttp(this);
    codec="UTF-8";

    connect(http, SIGNAL(requestFinished(int, bool)),
            this, SLOT(httpRequestFinished(int, bool)));
    connect(http, SIGNAL(responseHeaderReceived(const QHttpResponseHeader &)),
            this, SLOT(readResponseHeader(const QHttpResponseHeader &)));
    connect(http, SIGNAL(done(bool)),
            this, SLOT(finished(bool)));
}

Downloader::~Downloader() {
    delete http;
    qDeleteAll(bufferList);
}

void Downloader::addUrl(const QUrl &url) {
    //qDebug() << url.toEncoded();
    if (url.isValid()) {
        urlList << url;
    } else {
        qDebug() << "ERROR in function "+QString(Q_FUNC_INFO)+": Invalid URL: "+url.toString();
    }
}

void Downloader::removeUrl( const QUrl &url ) {
    urlList.removeAll( url );
}

void Downloader::removeUrlAt( int i ) {
    urlList.removeAt( i );
}

void Downloader::setUrl( const QUrl &url, int i ) {
    if ( urlList.isEmpty() ) {
        urlList << url;
        //  qDebug()<< url.toString();
    } else
        if ( i < urlList.size() ) {
            urlList[i]=url;
        } else {
            qDebug() << "ERROR in function "+QString(Q_FUNC_INFO)+": no such iterm: "<< i <<"!";
        }
}


//! start downloading from urlList
void Downloader::download() {
    htmlList.clear();
    bufferList.clear();
    idList.clear();

    if (urlList.isEmpty()) {
        qDebug() << "ERROR in function "+QString(Q_FUNC_INFO)+": urlList is empty!";
        return;
    }

    for (int i=0;i<urlList.size();i++) {
        bufferList << ( new QBuffer() ) ;
        http->setHost( urlList[i].host() );
        QByteArray array=QUrl::toPercentEncoding(urlList[i].toString(),"/:%?&=");
        qDebug() << QString(Q_FUNC_INFO) <<": "<< array;
        qDebug() <<"HOST: "<< urlList[i].host();
        qDebug() <<"PATH: "<< urlList[i].path();
        idList<<http->get( array, bufferList[i] );
        qDebug()<<"!!!idList!!!: "<<idList;
    }
}

//SLOTS

void Downloader::httpRequestFinished(int requestId, bool error) {

    if (error) {
        qDebug() << "ERROR in function "+QString(Q_FUNC_INFO);
        qDebug() << "Error maybe in "+http->currentRequest ().values().last().second+" ?";
        ERRORMSG="A csatlakozás nem sikerült: "+http->currentRequest().values().last().second;
        return;
    }
    
    int actReq=-1;

    for ( int i=0; i < idList.size(); i++ ) {
        if ( requestId == idList[i] ) {
            actReq=i;
            break;
        }
    }

    if ( actReq==-1 ) {
        return;
    }
    qDebug()<<"BUFFER_LIST_SIZE: "<<bufferList.size();
    bufferList[actReq]->close();

    QString str;
    QString site;
    QByteArray result=bufferList[actReq]->data();

    QTextStream in(&result);

    in.setCodec(codec.toAscii().data());

    /*!
     remove multiple whitespace and newline characters
    */
    while (!in.atEnd()) {
        in>>str;
        site.append(str+" ");
    }

    htmlList << site;
}

void Downloader::readResponseHeader(const QHttpResponseHeader &responseHeader) {
    qDebug() << "In function "+QString(Q_FUNC_INFO);
    codec="UTF-8";

    if ( responseHeader.hasContentType() ) {
        QString encoding = ((( responseHeader.value ("content-type") ).split(";")).last()).toUpper();
        if ( encoding.split("=").first().simplified() == "CHARSET" ) {
            codec = encoding.split("=").last();
            qDebug() << codec;
        }
    }
    if (responseHeader.statusCode() != 200) {
        ERRORMSG="ERROR in function "+QString(Q_FUNC_INFO)+": "+responseHeader.reasonPhrase();
        qDebug() << ERRORMSG;

        return;
    }
}

//! urlList downloads finished, emitting done(QStringList &) signal
void Downloader::finished(bool error) {
    qDebug() << "In function "+QString(Q_FUNC_INFO);
    if (error) {
        qDebug() << QString("Error(s) occured during download!");
        emit errorOccured(ERRORMSG);
        return;
    }
    emit done(htmlList);
}

